package com.quyunshuo.module.home.activity.main

import com.quyunshuo.edwinmusictwo.base.mvvm.m.BaseRepository
import com.quyunshuo.edwinmusictwo.network.HomeApiService
import com.quyunshuo.module.home.music.Music
import com.quyunshuo.module.home.music.toEntity
import com.quyunshuo.module.home.room.database.SumDataBase
import javax.inject.Inject

/**
 * 首页M层
 *
 * @author Qu Yunshuo
 * @since 5/25/21 5:42 PM
 */
class HomeRepository @Inject constructor() : BaseRepository() {
    @Inject
    lateinit var mApi: HomeApiService

    private val musicDao by lazy {
        SumDataBase.getInstance().musicDao()
    }

    suspend fun addLatelyMusic(music: Music){
        val currentTime = System.currentTimeMillis()

        // 检查音乐是否已存在
        val exists = musicDao.exists(music.id)

        if (exists) {
            // 如果音乐已存在，更新播放记录
            musicDao.updatePlayRecord(music.id, currentTime)
        } else {
            // 如果音乐不存在，转换为实体并插入
            val entity = music.toEntity().copy(
                lastPlayed = currentTime,
                playCount = 1
            )
            musicDao.insertOrUpdate(entity)
        }
    }

    fun getLatelyMusic()=musicDao.getRecentlyPlayed()


}